import websocket
import threading
import json

class Message:

    def __init__(self, framework):
        self._framework = framework
        self.message = None
        self.message_status = False
        self.message_task = threading.Thread(name="message_task", target=self.task)
        self.message_task.daemon = True
        self.message_task.start()
    
    # 消息服务任务
    def task(self):
        websocket.enableTrace(False)
        self.message = websocket.WebSocketApp("ws://127.0.0.1:10081", on_message=self.on_message, on_error=self.on_error, on_close=self.on_close)
        self.message.on_open = self.on_open
        self.message.run_forever()
    
    # 打开消息服务
    def on_open(self, ws):
        self.message_status = True
        self.write({"operate": "run_status", "status": "success"})
    
    # 收到消息服务发来的信息
    def on_message(self, ws, message):
        message_json = json.loads(message)
        # 视觉识别类消息
        if message_json["operate"] and message_json["operate"] == "vision":
            if self._framework.vision:
                self._framework.vision.vision_callback(message_json)
    
    # 向消息服务发送消息
    def write(self, message):
        if self.message is not None and self.message_status:
            self.message.send(json.dumps(message))
    
    # 向消息服务发送运行日志类消息
    def log(self, data):
        if self.message is not None and self.message_status:
            self.message.send(json.dumps({"operate": "run_log", "content": data}))
    
    # 消息服务出现错误时
    def on_error(self, ws, error):
        self.message = None

    # 消息服务关闭时
    def on_close(self, ws):
        self.message = None
    
